import socket

def broadcast_ack(port=50000, ack_message="ACK"):
    """
    向255.255.255.255广播ACK数据
    :param port: 广播端口(默认50000)
    :param ack_message: 要发送的ACK消息(默认"ACK")
    """
    try:
        # 创建UDP套接字
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        
        # 关键设置：启用广播选项
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
        
        # 设置超时防止阻塞（可选）
        sock.settimeout(0.5)
        
        # 转换为bytes类型
        message = ack_message.encode('utf-8')
        
        # 发送到广播地址 连续发送n次
        for i in range(10):
            sock.sendto(message, ('255.255.255.255', port))
            print(f"✅ 已广播ACK到255.255.255.255:{port}")
        
    except Exception as e:
        print(f"❌ 广播失败: {str(e)}")
    finally:
        sock.close()

if __name__ == "__main__":
    # 示例：广播自定义ACK消息
    broadcast_ack(port=12345, ack_message="DEVICE_ACK_123")